import { useRequest } from 'ahooks'
import { useSearchParams } from 'react-router-dom'
import { getQuestionListService } from '../services/question'
import {
  LIST_SEARCH_PARAM_KEY,
  LIST_PAGE_PARAM_KEY,
  LIST_PAGESIZE_PARAM_KEY,
  LIST_DEFAULT_PAGE_SIZE,
} from '../constant/index'

type OptionType = {
  isStar: boolean
  isDelete: boolean
}

function useLoadQuestionListData(opt: Partial<OptionType>) {
  const { isStar, isDelete } = opt

  //  获取url参数
  const [searchParams] = useSearchParams()

  //   useRequest内部就是useEffect 页面更新会执行两次
  const { data, loading, error, refresh } = useRequest(
    async () => {
      // 搜索关键词
      const keyword = searchParams.get(LIST_SEARCH_PARAM_KEY) || ''
      // 分页页码
      const page = parseInt(searchParams.get(LIST_PAGE_PARAM_KEY) || '') || 1
      // 分页大小
      const pageSize =
        parseInt(searchParams.get(LIST_PAGESIZE_PARAM_KEY) || '') || LIST_DEFAULT_PAGE_SIZE

      const data = await getQuestionListService({ keyword, isStar, isDelete, page, pageSize })
      return data //data中有data和total
    },
    {
      refreshDeps: [searchParams],
    }
  )
  return { data, loading, error, refresh }
}

export default useLoadQuestionListData
